// SPDX-License-Identifier: GPL-2.0-only
/*
 * ionapp_import.c
 *
 * It is a user space utility to receive android ion memory buffer fd
 * over unix domain socket IPC that can be exported by ionapp_export.
 * This acts like a client for ionapp_export.
 *
 * Copyright (C) 2017 Pintu Kumar <pintu.ping@gmail.com>
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "ionutils.h"
#include "ipckernel.h"

struct ion_buffer_info ion_bufs[DMA_BUFS_MAX_NUM] = {0};
wmark_dev_ioctl_t recv_fds_mgs;

void recv_msg_full_ion_bufs(struct ion_buffer_info *ion_bufs, wmark_dev_ioctl_t *mgs)
{
	int i = -1;
	for (i = 0; i < DMA_BUFS_MAX_NUM; i++)
	{
		ion_bufs[i].buffd = mgs->fds[i].fd;
		ion_bufs[i].buflen = mgs->buf_len;
		printf("Client fd = %d index = %d\n", mgs->fds[i].fd, i);
	}

	printf("%s buf_len=%d\n", __func__, mgs->buf_len);
}

int main(void)
{
	int ret, status;
	int sockfd, shared_fd;
	unsigned char *map_buf;
	unsigned long map_len;

	ipc_dev_info_t ipc_dev;

	/* This is the client part. Here 0 means client or importer */
	status = open_ipc_dev(&ipc_dev);
	if (status < 0)
	{
		fprintf(stderr, "No exporter exists...\n");
		ret = status;
		goto err_socket;
	}

	ret = dev_receive_fds(&ipc_dev, &recv_fds_mgs);
	if (ret < 0)
	{
		fprintf(stderr, "Failed: socket_receive_fd\n");
		goto err_recv;
	}

	recv_msg_full_ion_bufs(&ion_bufs, &recv_fds_mgs);

	ret = ion_import_buffer_fds(ion_bufs);
	if (ret < 0)
	{
		fprintf(stderr, "Failed: ion_use_buffer_fd\n");
		goto err_import;
	}

	while (1)
	{

		read_all_bufs(ion_bufs);
		// write_all_bufs(ion_bufs, "iiiiiiiiiiiiiiiiiiiiiiiii");
		write_buffer_str(ion_bufs[0].buffer, ion_bufs[0].buflen,"1111111111111111111");
		write_buffer_str(ion_bufs[1].buffer, ion_bufs[1].buflen,"2222222222222222222");
		write_buffer_str(ion_bufs[2].buffer, ion_bufs[2].buflen,"3333333333333333333");
		write_buffer_str(ion_bufs[3].buffer, ion_bufs[3].buflen,"4444444444444444444");
		

		usleep(10000);
	}

err_import:
	ion_close_buffer_fds(ion_bufs);
	// ion_close_buffer_fd(&info);
err_fd:
err_recv:
err_socket:
	close_ipc_dev(&ipc_dev);

	return ret;
}
